package com.stylefeng.guns.modular.train.controller;

import com.alibaba.fastjson.JSON;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.common.constant.MvcResult;
import com.stylefeng.guns.common.persistence.model.Dict;
import com.stylefeng.guns.common.persistence.model.Employee;
import com.stylefeng.guns.common.persistence.model.QualityGradeRule;
import com.stylefeng.guns.config.excel.ExcelExportStylerImpl;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.base.tips.ErrorTip;
import com.stylefeng.guns.core.base.tips.SuccessTip;
import com.stylefeng.guns.core.util.BeanUtils;
import com.stylefeng.guns.modular.system.service.IDictService;
import com.stylefeng.guns.modular.system.service.IQualityGradeRuleService;
import com.stylefeng.guns.modular.train.service.IEmployeeService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.common.persistence.model.ProqualifyTrainPoints;
import com.stylefeng.guns.modular.train.service.IProqualifyTrainPointsService;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.stylefeng.guns.common.constant.Const;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

/**
 * 职业资格积分控制器
 *
 * @author fengshuonan
 * @Date 2018-01-06 21:02:31
 */
@Controller
@RequestMapping("/proqualifyTrainPoints")
public class ProqualifyTrainPointsController extends BaseController {

    private String PREFIX = "/train/proqualifyTrainPoints/";

    @Autowired
    private IProqualifyTrainPointsService proqualifyTrainPointsService;

    @Autowired
    private IQualityGradeRuleService qualityGradeRuleService;
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IDictService dictService;

    private static List<ProqualifyTrainPoints> REPEAT = new ArrayList<>();

    /**
     * 跳转到ProQualifyPoints首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "proqualifyTrainPoints.html";
    }

    /**
     * 跳转到添加ProQualifyPoints
     */
    @RequestMapping("/proqualifyTrainPoints_add")
    public String proqualifyTrainPointsAdd(Model model) {
        List<QualityGradeRule> qualityGradeRuleList = qualityGradeRuleService.getByGradeType(Const.PRO_QUALIFY_TRAIN);


        List<Dict> proWorks =dictService.getChildByCode(Const.DICT_PRO_WORK);
        List<Dict> getWays =dictService.getChildByCode(Const.DICT_GET_WAY);
        List<Dict> isSames =dictService.getChildByCode(Const.DICT_IS_SAME);

        model.addAttribute("isSames",isSames);
        model.addAttribute("getWays",getWays);
        model.addAttribute("proWorks",proWorks);
        model.addAttribute("proqualifys",qualityGradeRuleList);
        model.addAttribute("integral",qualityGradeRuleList.get(0) == null ? 0 : qualityGradeRuleList.get(0).getIntegral());

        return PREFIX + "proqualifyTrainPoints_add.html";
    }

    /**
     * 跳转到修改ProQualifyPoints
     */
    @RequestMapping("/proqualifyTrainPoints_update/{proqualifyTrainPointsId}")
    public String proqualifyTrainPointsUpdate(@PathVariable String proqualifyTrainPointsId, Model model) {
        ProqualifyTrainPoints proqualifyTrainPoints = proqualifyTrainPointsService.selectById(proqualifyTrainPointsId);
        List<QualityGradeRule> qualityGradeRuleList = qualityGradeRuleService.getByGradeType(Const.PRO_QUALIFY_TRAIN);


        List<Dict> proWorks =dictService.getChildByCode(Const.DICT_PRO_WORK);
        List<Dict> getWays =dictService.getChildByCode(Const.DICT_GET_WAY);
        List<Dict> isSames =dictService.getChildByCode(Const.DICT_IS_SAME);

        model.addAttribute("isSames",isSames);
        model.addAttribute("getWays",getWays);
        model.addAttribute("proWorks",proWorks);
        model.addAttribute("proqualifys",qualityGradeRuleList);

        model.addAttribute("item",proqualifyTrainPoints);
        LogObjectHolder.me().set(proqualifyTrainPoints);
        return PREFIX + "proqualifyTrainPoints_edit.html";
    }

    /**
     * 获取ProQualifyPoints列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(Employee employee, Double min, Double max) {
        if(BeanUtils.checkFieldValueNull(employee) && min == null && max == null){
            return proqualifyTrainPointsService.selectList(null);
        }

        EntityWrapper<Employee> wrapper = new EntityWrapper<>();
        wrapper.setEntity(employee);
        List<Employee> employees = employeeService.selectList(wrapper);
        Set<String> empCodes = new HashSet<>();
        employees.forEach(e -> empCodes.add(e.getEmpCode()));

        List<ProqualifyTrainPoints> list = new ArrayList<>();
        if(!empCodes.isEmpty()){
            EntityWrapper<ProqualifyTrainPoints> nwWrapper = new EntityWrapper<>();
            nwWrapper.in("emp_code",empCodes);

            if(min != null || max != null){
                min = min == null ? 0.0 : min;
                max = max == null ? 9999.0 : max;

                nwWrapper.between("integral",min,max);
            }

            list = proqualifyTrainPointsService.selectList(nwWrapper);
        }

        return list;
    }
    /**
     * 新增ProQualifyPoints
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(ProqualifyTrainPoints proqualifyTrainPoints) {
        proqualifyTrainPoints.setCreateTime(new Date());
        proqualifyTrainPoints.setDataOrigin(Const.IMPORT_TYPE_SYS);

        proqualifyTrainPointsService.insert(proqualifyTrainPoints);
        return super.SUCCESS_TIP;
    }


    @RequestMapping(value = "/adds")
    @ResponseBody
    public Object adds(@RequestBody ProqualifyTrainPoints[] repeatData) {
        List<ProqualifyTrainPoints> proqualifyTrainPointss = Arrays.asList(repeatData);

        Map<String, String> gradeAndGradeCodes = qualityGradeRuleService.getMapGradeAndGradeCodeByType(Const.PRO_QUALIFY_TRAIN);
        Map<String, Double> points = qualityGradeRuleService.getMapGradeCodeAndIntegralByType(Const.PRO_QUALIFY_TRAIN);
        Date now = new Date();

        for (ProqualifyTrainPoints proqualifyTrainPoints : proqualifyTrainPointss) {
            proqualifyTrainPoints.setDataOrigin(Const.IMPORT_TYPE_XML);
            proqualifyTrainPoints.setCreateTime(now);
            String grade = gradeAndGradeCodes.get(proqualifyTrainPoints.getQualifyLevel());
            if(StringUtils.isEmpty(grade)){
                proqualifyTrainPoints.setIntegral(0.0);
            }else{
                proqualifyTrainPoints.setQualifyLevelCode(grade);
                proqualifyTrainPoints.setIntegral(points.get(proqualifyTrainPoints.getQualifyLevelCode()));
            }
        }

        proqualifyTrainPointsService.insertBatch(proqualifyTrainPointss);
        return super.SUCCESS_TIP;
    }

    /**
     * 删除ProQualifyPoints
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam String proqualifyTrainPointsId) {
        if(proqualifyTrainPointsId.contains(",")){
            List<String> ids = Arrays.asList(proqualifyTrainPointsId.split(","));
            proqualifyTrainPointsService.deleteBatchIds(ids);
        }else{
            proqualifyTrainPointsService.deleteById(proqualifyTrainPointsId);
        }
        return SUCCESS_TIP;
    }

    /**
     * 修改ProQualifyPoints
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(ProqualifyTrainPoints proqualifyTrainPoints) {
        proqualifyTrainPointsService.updateById(proqualifyTrainPoints);
        return super.SUCCESS_TIP;
    }

    /**
     * ProQualifyPoints详情
     */
    @RequestMapping(value = "/detail/{proqualifyTrainPointsId}")
    @ResponseBody
    public Object detail(@PathVariable("proqualifyTrainPointsId") String proqualifyTrainPointsId) {
        return proqualifyTrainPointsService.selectById(proqualifyTrainPointsId);
    }


    /**
     * 跳转到导入ProQualifyPoints
     */
    @RequestMapping("/proqualifyTrainPoints_import")
    public String proqualifyTrainPointsImport() {
        return PREFIX + "proqualifyTrainPoints_import.html";
    }

    /**
     * 导入ProQualifyPoints
     */
    @RequestMapping(value = "/import")
    @ResponseBody
    public Object imports(MultipartHttpServletRequest mutReq) {

        ImportParams params = new ImportParams();
        params.setStartRows(0);
        params.setTitleRows(1);

        int count = 2;
        try {
            List<ProqualifyTrainPoints> proqualifyTrainPointss = ExcelImportUtil.importExcel(mutReq.getFile("file").getInputStream(), ProqualifyTrainPoints.class, params);
            Date now = new Date();

            Map<String, String> gradeAndGradeCodes = qualityGradeRuleService.getMapGradeAndGradeCodeByType(Const.PRO_QUALIFY_TRAIN);
            Map<String, Double> points = qualityGradeRuleService.getMapGradeCodeAndIntegralByType(Const.PRO_QUALIFY_TRAIN);

            Map<String, String> nameAndCode = employeeService.getNameAndCode();
            List<ProqualifyTrainPoints> noRepeat = new ArrayList<>();
            List<ProqualifyTrainPoints> hasNameList = new ArrayList<>();

            for (ProqualifyTrainPoints proqualifyTrainPoints : proqualifyTrainPointss) {
                proqualifyTrainPoints.setDataOrigin(Const.IMPORT_TYPE_XML);
                proqualifyTrainPoints.setCreateTime(now);

                if(StringUtils.isEmpty(proqualifyTrainPoints.getEmpCode())) {
                    //姓名检测
                    if (nameAndCode.containsKey(proqualifyTrainPoints.getEmpName())) {
                        //有该姓名，检测是否重名
                        if (nameAndCode.get(proqualifyTrainPoints.getEmpName()).contains(",")) {
                            //有重名情况
                            proqualifyTrainPoints.setEmpCode(Const.DEFAULT_CODE);
                            REPEAT.add(proqualifyTrainPoints);
                        } else {
                            //无重名、正常插入
                            proqualifyTrainPoints.setEmpCode(nameAndCode.get(proqualifyTrainPoints.getEmpName()));

                            String grade = gradeAndGradeCodes.get(proqualifyTrainPoints.getQualifyLevel());
                            if(StringUtils.isEmpty(grade)){
                                proqualifyTrainPoints.setIntegral(0.0);
                            }else{
                                proqualifyTrainPoints.setQualifyLevelCode(grade);
                                proqualifyTrainPoints.setIntegral(points.get(proqualifyTrainPoints.getQualifyLevelCode()));
                            }

                            noRepeat.add(proqualifyTrainPoints);
                        }
                    } else {
                        throw new Exception("姓名为 " + proqualifyTrainPoints.getEmpName() + " 在员工管理中不存在!");
                    }
                }else{
                    String grade = gradeAndGradeCodes.get(proqualifyTrainPoints.getQualifyLevel());
                    if(StringUtils.isEmpty(grade)){
                        proqualifyTrainPoints.setIntegral(0.0);
                    }else{
                        proqualifyTrainPoints.setQualifyLevelCode(grade);
                        proqualifyTrainPoints.setIntegral(points.get(proqualifyTrainPoints.getQualifyLevelCode()));
                    }

                    hasNameList.add(proqualifyTrainPoints);
                }

                count++;
            }

            //不重复，先插入
            if(noRepeat.size() > 0){
                proqualifyTrainPointsService.insertBatch(noRepeat);
            }
            if(hasNameList.size() > 0){
                proqualifyTrainPointsService.insertBatch(hasNameList);
            }
            //处理重复数据
            if(!REPEAT.isEmpty()){
                MvcResult mvcResult = new MvcResult();
                mvcResult.setData(REPEAT);

                return mvcResult;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return new ErrorTip(400,"第"+ count+"条 " +e.getMessage());
        }

        SuccessTip successTip = super.SUCCESS_TIP;
        successTip.setMessage(String.format("成功插入%d", count-2)  + "条数据");
        return successTip;
    }

    @RequestMapping("/repeat")
    public String repeat(Model model){
        model.addAttribute("repeat", JSON.toJSONString(REPEAT));

        //消费后清空
        REPEAT = new ArrayList<>();
        return PREFIX + "repeat.html";
    }

    /**
     * 导出
     */
    @RequestMapping(value = "/export")
    @ResponseBody
    public void export(HttpServletRequest request, HttpServletResponse response) {
        try {
            List<ProqualifyTrainPoints> proqualifyTrainPoints= proqualifyTrainPointsService.selectList(null);
            ExportParams exportParams=new ExportParams("技能鉴定积分统计表", "技能鉴定积分统计表");
            exportParams.setStyle(ExcelExportStylerImpl.class);
            exportParams.setTitleHeight((short)14);
            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, ProqualifyTrainPoints.class, proqualifyTrainPoints);
            OutputStream outputStream=response.getOutputStream();
            String fileName="技能鉴定积分统计表.xls";
            response.addHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes(),"ISO-8859-1"));
            workbook.write(outputStream);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
